//
//  KeHuXiangQingGenJinJiLuViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/17.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "KeHuXiangQingGenJinJiLuViewController.h"
#import "KeHuXiangQingGenJinJiLuTableViewCell.h"

#import "YuYinBoFangView.h"

#import "AppDelegate.h"

#import "LiaoTianWenJianChaKanViewController.h"
#import "YuYinBoFangView.h"
#import "ZBNetworking.h"
#import "GenJinJiLuViewController.h"
@interface KeHuXiangQingGenJinJiLuViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UIDocumentPickerDelegate>{
    YuYinBoFangView *yuYinView;
    int page;
    NSMutableArray *dataSource;
    
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;

@end

@implementation KeHuXiangQingGenJinJiLuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.customNavBar.hidden = YES;
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"KeHuXiangQingGenJinJiLuTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeHuXiangQingGenJinJiLuTableViewCell"];
    
    yuYinView = [YuYinBoFangView view];
    [[AppDelegate shareInstance].window addSubview:yuYinView];
  
    yuYinView.frame = CGRectMake(0, ScreenHeight-107-30, ScreenWidth, 107);
    yuYinView.hidden = YES;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downRefresh];
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
    
    [self downRefresh];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    yuYinView.hidden = YES;
    [yuYinView closeVoice];
}
//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void)downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
    [paraDic setValue:@"2" forKey:@"crmType"];
    [paraDic setValue:@"" forKey:@"activityType"];
    [paraDic setValue:_customerId forKey:@"activityTypeId"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmActivity/getAppCrmActivityPageList" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                NSMutableArray *tempArray = [NSMutableArray array];
                for (NSDictionary *tep in array) {
                    if([[tep objectForKey:@"list"] isKindOfClass:[NSArray class]]){
                        [tempArray addObjectsFromArray:[tep objectForKey:@"list"]];
                    }
                }
                dataSource = [NSMutableArray arrayWithArray:tempArray];
                if ([array count]> 9) {
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                    if(dataSource.count == 0){
                        _mainTableView.mj_footer.hidden = YES;
                    }else{
                        _mainTableView.mj_footer.hidden = NO;
                    }
                }
            }else {
                if (array.count > 0) {
                    NSMutableArray *tempArray = [NSMutableArray array];
                    for (NSDictionary *tep in array) {
                        if([[tep objectForKey:@"list"] isKindOfClass:[NSArray class]]){
                            [tempArray addObjectsFromArray:[tep objectForKey:@"list"]];
                        }
                    }
                    [dataSource addObjectsFromArray:tempArray];
                }
                
                if ([array count]> 9) {
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KeHuXiangQingGenJinJiLuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeHuXiangQingGenJinJiLuTableViewCell"];
    AllModel *model = [[AllModel alloc] init];
    model.modelInfoDictionary = dataSource[indexPath.row];
    cell.model = model;
    
    cell.manageClickBlock = ^(NSDictionary * _Nonnull resultDic, NSInteger manageType) {
        if(manageType == 101){
//                预览
            if([GetHandleString(resultDic, @"urlImage") containsString:@".mp3"]){
                yuYinView.hidden = NO;
                yuYinView.titleLabel.text = GetHandleString(resultDic, @"name");
                yuYinView.voiceUrl = GetHandleString(resultDic, @"urlImage");
            }else{
                LiaoTianWenJianChaKanViewController *yuLan = [[LiaoTianWenJianChaKanViewController alloc] init];
                yuLan.loadUrl = GetHandleString(resultDic, @"urlImage");
                [self pushViewController:yuLan];
            }
        }else if(manageType == 102){
//                下载
            [self downLoadWithFilePath:GetHandleString(resultDic, @"urlImage")];
        }else if(manageType == 103){
            //                编辑
            GenJinJiLuViewController *genJin = [[GenJinJiLuViewController alloc] init];
            genJin.dataInfoDictionary = dataSource[indexPath.row];
            genJin.activityTypeId = _customerId;
            genJin.addSuccessClickBlock = ^{
                [self downRefresh];
            };
            [self pushViewController:genJin];
        }
    };
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    AllModel *model = [[AllModel alloc] init];
    model.modelInfoDictionary = dataSource[indexPath.row];
    return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[KeHuXiangQingGenJinJiLuTableViewCell class] contentViewWidth:[self cellContentViewWith]];
}
#pragma mark - 下载文件

- (void)downLoadWithFilePath:(NSString *)filePath {
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 11) {
        
    } else {
        [ZZPUtils showWarning:@"下载文件要求手机系统版本在11.0以上"];
        return;
    }

    
    [[ZZPRequest getWebUtil] addAnimation];
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest * request) {
         request.url =  filePath;
         request.methodType=ZBMethodTypeDownLoad;
         request.downloadState=ZBDownloadStateStart;//开始 //ZBDownloadStateStop暂停
     } progress:^(NSProgress * _Nullable progress) {
         NSLog(@"onProgress: %.2f", 100.f * progress.completedUnitCount/progress.totalUnitCount);
     } success:^(id  responseObject,ZBURLRequest * request) {
         NSLog(@"ZBMethodTypeDownLoad 此时会返回存储路径文件: %@", responseObject);
         
         [[ZZPRequest getWebUtil] hiddenAnimation];
         
          //在任何地方拿到下载文件
         NSString *file=[ZBRequestManager getDownloadFileForKey:request.url];
  
         NSLog(@"file:%@",file)
         
         UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:file] inMode:UIDocumentPickerModeExportToService];
         // 设置代理
         documentPickerVC.delegate = self;
         // 设置模态弹出方式
         documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
         [self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
    
     } failure:^(NSError * _Nullable error) {
         NSLog(@"error: %@", error);
         
         [[ZZPRequest getWebUtil] hiddenAnimation];
     }];
}
 

 
#pragma mark - UIDocumentPickerDelegate
 
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            // 读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                // 读取出错
            } else {
                // 上传
                NSLog(@"fileName : %@", fileName);
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授权失败
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

